package com.strawberry.chat2.views.webpImage;

import android.content.ContentResolver;
import android.net.Uri;
import android.support.rastermill.FrameSequenceDrawable;
import android.widget.ImageView;

import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2019/3/5.
 */

public class WebpImageManager extends SimpleViewManager<ImageView> {
    private static final String GIFVIEW_MANAGER_NAME = "WebpImage";
    private static final String PROP_SRC = "source";

    private ThemedReactContext mContext;

    @Override
    public String getName() {
        return GIFVIEW_MANAGER_NAME;
    }

    @Override
    protected ImageView createViewInstance(ThemedReactContext reactContext) {
        this.mContext = reactContext;
        final ImageView ImageView = new ImageView(reactContext);
        return ImageView;
    }

    @ReactProp(name = PROP_SRC)
    public void setSrc(final ImageView imageView, ReadableMap source){
        if(source.hasKey("uri")) {
            String url = source.getString("uri");
            ContentResolver resolver = mContext.getContentResolver();
            InputStream inStream = null;
            try {
                inStream=resolver.openInputStream(Uri.parse(url));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            };
            if(inStream != null){
                try{
                    final FrameSequenceDrawable drawable = new FrameSequenceDrawable(inStream);
                    drawable.setLoopCount(1);
                    drawable.setLoopBehavior(FrameSequenceDrawable.LOOP_FINITE);
                    drawable.setOnFinishedListener(new FrameSequenceDrawable.OnFinishedListener() {
                        @Override
                        public void onFinished(FrameSequenceDrawable frameSequenceDrawable) {
                            imageView.setImageDrawable(null);
                            mContext
                                    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                                    .emit("onAnimFinish", null);
                        }
                    });
                    imageView.setImageDrawable(drawable);
                }catch (Exception e){

                }
            }
        }
    }
}
